/**
 *  封装select2下拉选择组件(请先引入Jquery、select2.js文件)
 * 使用方式：$(element).selectQuery(options);
 *
 * @author zsp
 * @date 2017-12-15
 */
;
(function($) {
	$.fn.extend({
		selectQuery: function(options) {
			options = $.extend({}, defaultOptions = {
				url: '',
				defaultText: '请选择',
				defaultMinLength: 0, //默认输入多少个字符启动查询
				optionValue: '',
				optionText: '',
				queryParams: {}
			}, options || {});

			if (!options.url) {
				console.error("please set url of upload ajax ！");
				return;
			}

			$(this).select2({
				placeholder: options.defaultText,
				language: "zh-CN",
				ajax: {
					url: options.url,
					type: 'POST',
					dataType: 'json',
					cache: true,
					delay: 250,
					data: function(params) {
						return $.extend({
							pageNo: params.page,
							pageSize: 10,
							queryName: params.term
						}, options.queryParams);
					},
					processResults: function(data, params) {
						params.page = params.page || 1;
						var items = "";
						if (data && data.data) {
							items = $.map(data.data.list, function(obj) {
								var option = {};
								option.id = obj[options.optionValue];
								option.text = obj[options.optionText];
								return option;
							});
						}
						return {
							results: items,
							pagination: {
								more: params.page < ((data.data.total / 10) + 1)
							}
						};
					},
				},
				escapeMarkup: function(markup) {
					return markup;
				},
				minimumInputLength: options.defaultMinLength
			});
		}
	});
})(jQuery);